const express = require('express');
const { body, param, query, validationResult } = require('express-validator');
const User = require('../models/User');
const Role = require('../models/Role');
const Department = require('../models/Department');

const router = express.Router();

// 验证错误处理中间件
const handleValidationErrors = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: errors.array()
    });
  }
  next();
};

// 获取用户列表
router.get('/', [
  query('page').optional().isInt({ min: 1 }),
  query('limit').optional().isInt({ min: 1, max: 100 }),
  query('search').optional().isString(),
  query('status').optional().isString(),
  query('roleId').optional().isInt(),
  query('deptId').optional().isInt(),
  handleValidationErrors
], async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '', status, roleId, deptId } = req.query;
    const result = await User.findAll(page, limit, { search, status, roleId, deptId });
    res.json({ success: true, message: '获取用户列表成功', data: result });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取单个用户
router.get('/:id', [
  param('id').isInt({ min: 1 }),
  handleValidationErrors
], async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) return res.status(404).json({ success: false, message: '用户不存在' });
    res.json({ success: true, message: '获取用户成功', data: user });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 创建用户（支持多角色）
router.post('/', [
  body('username').isString().notEmpty(),
  body('password').isString().notEmpty(),
  body('email').optional().isEmail(),
  body('phone').optional().isString(),
  body('department_id').isInt({ min: 1 }),
  body('role_ids').isArray({ min: 1 }).withMessage('至少分配一个角色'),
  body('role_ids.*').isInt({ min: 1 }).withMessage('角色ID必须是正整数'),
  handleValidationErrors
], async (req, res) => {
  try {
    const userData = req.body;
    const { role_ids, ...userInfo } = userData;

    // 验证部门是否存在
    const department = await Department.findById(userData.department_id);
    if (!department) return res.status(400).json({ success: false, message: '指定的部门不存在' });

    // 验证所有角色是否存在
    for (const roleId of role_ids) {
      const role = await Role.findById(roleId);
      if (!role) {
        return res.status(400).json({ 
          success: false, 
          message: `角色ID ${roleId} 不存在` 
        });
      }
    }

    // 创建用户（不包含role_id，因为要支持多角色）
    const newUser = await User.create(userInfo);
    
    // 分配多角色
    await User.setRoles(newUser.id, role_ids);

    // 返回用户信息（包含角色信息）
    const userWithRoles = await User.findById(newUser.id);
    const userRoles = await User.getRoles(newUser.id);
    
    res.status(201).json({ 
      success: true, 
      message: '创建用户成功', 
      data: {
        ...userWithRoles,
        role_ids: userRoles
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 更新用户
router.put('/:id', [
  param('id').isInt({ min: 1 }),
  body('username').optional().isString().notEmpty(),
  body('password').optional().isString().notEmpty(),
  body('email').optional().isEmail(),
  body('phone').optional().isString(),
  body('status').optional().isIn(['active', 'inactive']),
  body('role_id').optional().isInt({ min: 1 }),
  body('department_id').optional().isInt({ min: 1 }),
  handleValidationErrors
], async (req, res) => {
  try {
    const { id } = req.params;
    const userData = req.body;

    if (userData.role_id) {
      const role = await Role.findById(userData.role_id);
      if (!role) return res.status(400).json({ success: false, message: '指定的角色不存在' });
    }

    if (userData.department_id) {
      const department = await Department.findById(userData.department_id);
      if (!department) return res.status(400).json({ success: false, message: '指定的部门不存在' });
    }

    const updatedUser = await User.update(id, userData);
    res.json({ success: true, message: '更新用户成功', data: updatedUser });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 修改密码
router.patch('/:id/password', [
  param('id').isInt({ min: 1 }),
  body('password').isLength({ min: 6 }),
  handleValidationErrors
], async (req, res) => {
  try {
    await User.updatePassword(req.params.id, req.body.password);
    res.json({ success: true, message: '更新密码成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 删除单个用户
router.delete('/:id', [
  param('id').isInt({ min: 1 }),
  handleValidationErrors
], async (req, res) => {
  try {
    await User.delete(req.params.id);
    res.json({ success: true, message: '删除用户成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 批量删除
router.delete('/', [
  body('ids').isArray({ min: 1 }),
  body('ids.*').isInt({ min: 1 }),
  handleValidationErrors
], async (req, res) => {
  try {
    const deletedCount = await User.deleteMultiple(req.body.ids);
    res.json({ success: true, message: `成功删除 ${deletedCount} 个用户`, data: { deletedCount } });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取统计信息
router.get('/stats/overview', async (req, res) => {
  try {
    const stats = await User.getStats();
    res.json({ success: true, message: '获取用户统计成功', data: stats });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 创建选项（角色与部门）
router.get('/options/creation', async (req, res) => {
  try {
    const [roles, departments] = await Promise.all([
      Role.getAllRoles(),
      Department.getAllDepartments()
    ]);
    res.json({ success: true, message: '获取创建选项成功', data: { roles, departments } });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取用户已分配角色ID
router.get('/:id/roles', async (req, res) => {
  try {
    const roleIds = await User.getRoles(req.params.id);
    res.json({ success: true, data: roleIds });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 分配角色
router.put('/:id/roles', async (req, res) => {
  try {
    const { roleIds } = req.body;
    await User.setRoles(req.params.id, roleIds);
    res.json({ success: true, message: '分配角色成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取用户所有菜单（树结构）
router.get('/:id/menus', async (req, res) => {
  try {
    const menus = await User.getMenus(req.params.id);
    res.json({ success: true, data: menus });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

module.exports = router;
